package pers.llc.css.juc;


import java.util.concurrent.*;

/**
 * 用于实现两个人之间的数据交换，每个人在完成一定的事务后想与对方交换数据，
 * 第一个先拿出数据的人将一直等待第二个人拿着数据到时才能彼此交换
 *
 * @author lls
 * @time 2018-10-02
 */
public class MyExchanger {

    public static void main(String[] args) {
        ExecutorService service = new ThreadPoolExecutor(3, 4, 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        final Exchanger exchanger = new Exchanger();

        service.execute(() -> {
            try {
                String str = "test";
                System.out.println("线程" + Thread.currentThread().getName() +
                        "正在把数据" + str + "换出去");

                Thread.sleep(3000);
                String str1 = (String) exchanger.exchange(str);
                System.out.println("线程" + Thread.currentThread().getName() +
                        "换回来的数据为" + str1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        service.execute(() -> {
            try {
                String tes = "testtt";
                System.out.println("线程" + Thread.currentThread().getName() +
                        "正在把数据" + tes + "换出去");

                Thread.sleep(3000);
                String tes1 = (String) exchanger.exchange(tes);
                System.out.println("线程" + Thread.currentThread().getName() +
                        "换回来的数据为" + tes1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
    }
}
